/**
 * 
 */
package controler;

import interfaces.Client_ITF;
import interfaces.Serveur_ITF;

import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import rmiClient.Client_IMPL;
import rmiServeur.ServerBusy;
import view.MainFrame;
import view.MultipleStringDialog;
import view.MultipleStringDialog.ExitOption;
import view.ThreadCheckElectionResult;

/**
 * @author arthur
 * 
 */
public class Launcher {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String ipLocal = null;
		String moviesFolder = null;
		boolean clientAdded = false;

		// try {
		// URL u = new URL("http://lufrima.free.fr/ip.php");
		// InputStream i = u.openStream();
		// BufferedReader b = new BufferedReader(new InputStreamReader(i));
		// ipLocal = b.readLine();
		// } catch (IOException e) {
		// JOptionPane.showMessageDialog(null,
		// "Nous n'avons pas pu récupéré votre adresse IP");
		// System.exit(10);
		// }

		try {
			ipLocal = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String[] labels = { "IP du serveur", "Port du serveur",
				"Identifiant local", "Score local" };
		MultipleStringDialog msd = new MultipleStringDialog(null,
				"Configuration Serveur", true, labels,
				"Veuillez entrer l'adresse Ip et port le port du serveur du à contacter");
		msd.setVisible(true);

		if (msd.getExitOption() == ExitOption.VALID) {
			String[] results = msd.getResults();
			Serveur_ITF server = null;
			Client_IMPL c = null;

			try {
				server = (Serveur_ITF) Naming.lookup("rmi://" + results[0]
						+ ":" + results[1] + "/server");
			} catch (MalformedURLException e) {
				JOptionPane.showMessageDialog(null,
						"L'adresse ip et/ou le port n'est pas au bon format");
				System.exit(1);
			} catch (RemoteException e) {
				JOptionPane.showMessageDialog(null,
						"Une erreure à eu lieu sur le serveur");
				System.exit(2);
			} catch (NotBoundException e) {
				JOptionPane.showMessageDialog(null,
						"Le serveur n'a pu être contacté");
				System.exit(3);
			}

			JFileChooser jfc = new JFileChooser("~");
			jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

			int result = jfc.showDialog(null, "Choisissez le dossier des vidéos");

			if (result == JFileChooser.APPROVE_OPTION) {
				try {
					moviesFolder = jfc.getSelectedFile().getCanonicalPath();
				} catch (IOException e) {
					JOptionPane
							.showMessageDialog(null,
									"Erreure lors de la selection du dossier des vidéo");
					System.exit(6);
				}
			} else {
				JOptionPane.showMessageDialog(null,
						"Erreure lors de la selection du dossier des vidéo");
				System.exit(7);
			}

			try {
				c = new Client_IMPL(server, Integer.parseInt(results[2]),
						Integer.parseInt(results[3]), ipLocal, moviesFolder);
			} catch (RemoteException e) {
				// this exception cannot occur locally
				System.exit(-1);
			}

			while (!clientAdded) {
				try {
					server.addClient(c);
					clientAdded = true;
				} catch (ServerBusy e) {
					int retry = JOptionPane.showOptionDialog(null,
							"Le serveur est occuper, voulez-vous réessayer",
							"Serveur occupé", JOptionPane.YES_NO_OPTION,
							JOptionPane.QUESTION_MESSAGE, null, null, null);
					if (retry == JOptionPane.NO_OPTION) {
						System.exit(0);
					}

				} catch (RemoteException e) {
					JOptionPane
							.showMessageDialog(null,
									"Une erreur sur le serveur a empeché votre inscription");
					System.exit(4);
				}
			}

			try {
				for (Client_ITF newNeighbor : server.getNeighbors(c)) {
					c.getNeighbors().put(newNeighbor.getId(), newNeighbor);
				}
			} catch (RemoteException e) {
				JOptionPane
						.showMessageDialog(null,
								"Une erreure sur le serveur à empeché la récupération de vos voisins");
				System.exit(5);
			}

			MainFrame mf = new MainFrame(c);

			ScheduledExecutorService executor = Executors
					.newSingleThreadScheduledExecutor();
			executor.scheduleWithFixedDelay(
					new ThreadCheckElectionResult(mf, c), 2, 1,
					TimeUnit.SECONDS);
			mf.setVisible(true);

		} else {
			System.exit(0);
		}
	}

}
